package com.truyentranh.modules.tamdiem;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.truyentranh.R;
import com.truyentranh.controls.AdsViewControl;
import com.truyentranh.controls.DataCachedControl;
import com.truyentranh.data.TamDiemMetalData;
import com.truyentranh.main.AdsBussiness;
import com.truyentranh.network.APIRequestWorker;
import com.truyentranh.network.Request;
import com.truyentranh.network.RequestListener;
import com.truyentranh.requester.TamDiemRequester;
import com.truyentranh.utils.Logger;

public class TamDiemActivity extends Activity implements RequestListener, OnItemClickListener {

	LinearLayout loadingPage = null;
	LinearLayout loadingError = null;
	LinearLayout mainContent = null;
	AdsViewControl prviewTamDiem = null;
	GridView imageListView = null;
	TamDiemRenderAdapter tamDiemRenderAdapter = null;
	boolean isLoading = false;

	public void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.khoanh_activity_layout);

		loadingPage = (LinearLayout) findViewById(R.id.loadingpagetamdiem);
		loadingError = (LinearLayout) findViewById(R.id.loadingError);
		mainContent = (LinearLayout) findViewById(R.id.mainContent);
		prviewTamDiem = (AdsViewControl) findViewById(R.id.prviewTamDiem);
		imageListView = (GridView) findViewById(R.id.imageListView);

		prviewTamDiem.setVisibility(View.INVISIBLE);
		loadingError.setVisibility(View.INVISIBLE);

		TextView textView = (TextView) findViewById(R.id.titleActivity);
		textView.setText("Kho ảnh");

		Button button = (Button) findViewById(R.id.btnMoreFunctions);
		button.setBackgroundResource(R.drawable.refresh_indicator);
		button.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (!isLoading) {
					isLoading = true;

					imageListView.setVisibility(View.INVISIBLE);
					loadingError.setVisibility(View.GONE);
					loadingPage.setVisibility(View.VISIBLE);
					DataCachedControl.getInstance().clearCached(DataCachedControl.TAM_DIEM_TOPIC_LIST);
					TamDiemRequester requester = TamDiemRequester.getLists(TamDiemActivity.this);
					APIRequestWorker.getInstance().addAPIRequest(requester);
				}
			}
		});

		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					APIRequestWorker.getInstance().clearAllRequests();
					finish();
				}
			});
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			APIRequestWorker.getInstance().clearAllRequests();
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	void doAdsByServer() {
		AdsBussiness.getInstance().doGetAdsFromServer(this, prviewTamDiem);
	}

	@Override
	protected void onStart() {
		super.onStart();
		
		onStartUp();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		onStartUp();
	}

	@SuppressWarnings("unchecked")
	private void onStartUp() {
		init();
		final Object dataCached = DataCachedControl.getInstance().getCached(DataCachedControl.TAM_DIEM_TOPIC_LIST);
		if (dataCached != null && dataCached instanceof ArrayList<?>) {

			runOnUiThread(new Runnable() {
				public void run() {

					imageListView.setOnItemClickListener(TamDiemActivity.this);
					loadingError.setVisibility(View.GONE);
					loadingPage.setVisibility(View.GONE);
					imageListView.setVisibility(View.VISIBLE);

					fillDataIntoAdapter((ArrayList<TamDiemMetalData>) dataCached);
					isLoading = false;

					doAdsByServer();
				}
			});
		} else {
			isLoading = true;
			TamDiemRequester requester = TamDiemRequester.getLists(this);
			APIRequestWorker.getInstance().addAPIRequest(requester);
		}
	}

	void init() {
	}

	void fillDataIntoAdapter(ArrayList<TamDiemMetalData> arrayList) {
		if (tamDiemRenderAdapter == null) {
			tamDiemRenderAdapter = new TamDiemRenderAdapter(this, 1, 1, arrayList);
			imageListView.setAdapter(tamDiemRenderAdapter);
		} else {
			tamDiemRenderAdapter.setNewData(arrayList);
			tamDiemRenderAdapter.notifyDataSetChanged();
		}
	}

	public void onRequestComplete(Request request) {
		// TODO Auto-generated method stub
		if (request instanceof TamDiemRequester) {
			final ArrayList<TamDiemMetalData> arrayList = ((TamDiemRequester) request).getDataList();
			DataCachedControl.getInstance().putCached(DataCachedControl.TAM_DIEM_TOPIC_LIST, arrayList);
			runOnUiThread(new Runnable() {
				public void run() {

					imageListView.setOnItemClickListener(TamDiemActivity.this);
					loadingError.setVisibility(View.GONE);
					loadingPage.setVisibility(View.GONE);
					imageListView.setVisibility(View.VISIBLE);

					fillDataIntoAdapter(arrayList);
					isLoading = false;

					doAdsByServer();
				}
			});
		}
	}

	public void onRequestFailed(String errorMsg, Request request) {
		runOnUiThread(new Runnable() {

			public void run() {
				loadingPage.setVisibility(View.GONE);
				loadingError.setVisibility(View.VISIBLE);

				isLoading = false;

				doAdsByServer();
			}
		});
	}

	public void onItemClick(AdapterView<?> adapterView, View arg1, int index, long arg3) {
		if (tamDiemRenderAdapter != null) {
			final String id = tamDiemRenderAdapter.getItem(index).getId();
			if (id != null && !"".equals(id)) {
				Intent intent = new Intent(getApplication(), TamDiemDetailModulesActivity.class);
				intent.putExtra("ID", id);
				intent.putExtra("NAME", tamDiemRenderAdapter.getItem(index).getName());				
				startActivity(intent);
			}
		}
	}
}
